#--*--coding=utf-8--*--
#MaterialCodeGenerator.py
import sys
import json
import sqlite3
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QComboBox, QMessageBox
from PySide6.QtCore import Qt

import chardet

class MaterialCodeGenerator(QWidget):
    def __init__(self):
        super().__init__()
        
        self.initUI()
        self.load_rules()

    def initUI(self):
        layout = QVBoxLayout()

        # 创建并布局第1组的选择框
        self.label_part1 = QLabel('选择第1组类别:', self)
        layout.addWidget(self.label_part1)

        self.combo_box_part1 = QComboBox(self)
        self.combo_box_part1.currentIndexChanged.connect(self.update_code)
        layout.addWidget(self.combo_box_part1)

        # 创建并布局第2组的选择框
        self.label_part2 = QLabel('选择第2组类别:', self)
        layout.addWidget(self.label_part2)

        self.combo_box_part2 = QComboBox(self)
        self.combo_box_part2.currentIndexChanged.connect(self.update_code)
        layout.addWidget(self.combo_box_part2)

        # 创建并布局第3组的选择框
        self.label_part3 = QLabel('选择第3组类别:', self)
        layout.addWidget(self.label_part3)

        self.combo_box_part3 = QComboBox(self)
        self.combo_box_part3.currentIndexChanged.connect(self.update_code)
        layout.addWidget(self.combo_box_part3)

        # 创建并布局最终编码显示
        self.label_code = QLabel('生成的物料编码:', self)
        layout.addWidget(self.label_code)

        self.code_display = QLabel('', self)
        self.code_display.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.code_display)

        
        # 复制按钮
        self.copy_button = QPushButton('复制编码', self)
        self.copy_button.clicked.connect(self.copy_code_to_clipboard)
        layout.addWidget(self.copy_button)

        # 创建并布局生成按钮
        generate_button = QPushButton('生成编码', self)
        generate_button.clicked.connect(self.generate_code)
        layout.addWidget(generate_button)

        
        self.setLayout(layout)
        self.setWindowTitle('物料编码生成器')
        self.show()

    def load_rules(self):
        # 从JSON文件加载编码规则
        with open('rules.json', 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            self.encoding = result['encoding']
            
        with open('rules.json', 'r', encoding=self.encoding) as f:
            self.rules = json.load(f)

        # 填充下拉列表
        for part in ['part1', 'part2', 'part3']:
            combo_box = getattr(self, f'combo_box_{part}')
            for category in self.rules[part]:
                combo_box.addItem(category['name'], category['code'])

        # 连接至SQLite数据库
        conn = sqlite3.connect('material.db')
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS materials (id INTEGER PRIMARY KEY, code TEXT)''')
        conn.commit()
        conn.close()

    def update_code(self):
        # 根据选择更新显示的代码
        part1_code = self.combo_box_part1.currentData()
        part2_code = self.combo_box_part2.currentData()
        part3_code = self.combo_box_part3.currentData()

        if part1_code and part2_code and part3_code:
            code = f"{part1_code}.{part2_code}.{part3_code}"
            self.code_display.setText(code)

    def generate_code(self):
        # 获取当前选择的代码
        part1_code = self.combo_box_part1.currentData()
        part2_code = self.combo_box_part2.currentData()
        part3_code = self.combo_box_part3.currentData()

        if not (part1_code and part2_code and part3_code):
            QMessageBox.critical(self, "错误", "请完成所有类别的选择")
            return

        code = f"{part1_code}.{part2_code}.{part3_code}"

        # 将生成的编码保存到数据库
        self.save_to_database(code)
        QMessageBox.information(self, "成功", f"物料编码 {code} 已生成并保存")

    def save_to_database(self, code):
        # 将生成的编码保存到数据库
        conn = sqlite3.connect('material.db')
        c = conn.cursor()
        c.execute("INSERT INTO materials (code) VALUES (?)", (code,))
        conn.commit()
        conn.close()
        
    def copy_code_to_clipboard(self):
        clipboard = QApplication.clipboard()
        clipboard.setText(self.generated_code)
        QMessageBox.information(self, '提示', '编码已复制到剪贴板！')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MaterialCodeGenerator()
    sys.exit(app.exec())

